﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.AspNet.Membership.OpenAuth;

namespace MFAAzureTest.Account
{
    public partial class Manage : System.Web.UI.Page
    {
        protected string SuccessMessage
        {
            get;
            private set;
        }

        protected bool CanRemoveExternalLogins
        {
            get;
            private set;
        }

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine the sections to render
                var hasLocalPassword = OpenAuth.HasLocalPassword(User.Identity.Name);
                //setPassword.Visible = !hasLocalPassword;
                //changePassword.Visible = hasLocalPassword;

                //CanRemoveExternalLogins = hasLocalPassword;

                //// Render success message
                //var message = Request.QueryString["m"];
                //if (message != null)
                //{
                //    // Strip the query string from action
                //    Form.Action = ResolveUrl("~/Account/Manage");

                //    SuccessMessage =
                //        message == "ChangePwdSuccess" ? "Your password has been changed."
                //        : message == "SetPwdSuccess" ? "Your password has been set."
                //        : message == "RemoveLoginSuccess" ? "The external login was removed."
                //        : String.Empty;
                //    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                //}
            }

        }

        //protected void setPassword_Click(object sender, EventArgs e)
        //{
        //    if (IsValid)
        //    {
        //        var result = OpenAuth.AddLocalPassword(User.Identity.Name, password.Text);
        //        if (result.IsSuccessful)
        //        {
        //            Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
        //        }
        //        else
        //        {

        //            ModelState.AddModelError("NewPassword", result.ErrorMessage);

        //        }
        //    }
        //}

        protected void validateToken_Click(object sender, EventArgs e)
        {

            if (IsValid)
            {
                
                // for a real storage account:
                String dataConnectionString = "DefaultEndpointsProtocol=https;AccountName=aliciaauthy;AccountKey=UihKsy9AYk9R/UFMhpnxs9Ju459H+BVaUROJ5SJuGL7M2y8ILV8QwmeEK1gw+ga+AYwcF9nMjq5VPsztoGHT1Q==";
                String tableName = "azure";
                CloudStorageAccount account = CloudStorageAccount.Parse(dataConnectionString);
                // create the table client
                CloudTableClient tableClient = account.CreateCloudTableClient();
                // create the table if it doesn't exist
                CloudTable table = tableClient.GetTableReference(tableName);

                TableQuery query = new TableQuery().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, User.Identity.Name));
                String phoneNumber = " ";

                foreach (var entity in table.ExecuteQuery(query))
                {
                    phoneNumber = entity.RowKey;
                }

                string otp = "";
                int callStatus = 0;
                int errorId = 0;

                // note that the phone number contains no dashes, spaces, or any other
                // special characters.
                PfAuthParams pfAuthParams = new PfAuthParams();
                pfAuthParams.Username = User.Identity.Name;
                pfAuthParams.Phone = phoneNumber;
                //pfAuthParams.Extension = "00353";
                //pfAuthParams.ApplicationName = txtApplicationName.Text;
               // pfAuthParams.DeviceToken = txtDeviceToken.Text;
                //if (rbApns.Checked) pfAuthParams.NotificationType = pf_auth.NOTIFICATION_TYPE_APNS;
                //if (rbC2dm.Checked) pfAuthParams.NotificationType = pf_auth.NOTIFICATION_TYPE_C2DM;
                //if (rbGcm.Checked) 
                pfAuthParams.NotificationType = pf_auth.NOTIFICATION_TYPE_GCM;
                //if (rbMpns.Checked) pfAuthParams.NotificationType = pf_auth.NOTIFICATION_TYPE_MPNS;
                //if (rbBps.Checked) pfAuthParams.NotificationType = pf_auth.NOTIFICATION_TYPE_BPS;
               // pfAuthParams.AccountName = txtAccountName.Text;
                //if (rbStandard.Checked) 
                pfAuthParams.Mode = pf_auth.MODE_STANDARD;
                //if (rbPin.Checked) pfAuthParams.Mode = pf_auth.MODE_PIN;
                //if (rbVoiceprint.Checked) pfAuthParams.Mode = pf_auth.MODE_VOICEPRINT;
                //if (rbSmsTwoWayOtp.Checked) pfAuthParams.Mode = pf_auth.MODE_SMS_TWO_WAY_OTP;
                //if (rbSmsTwoWayOtpPlusPin.Checked) pfAuthParams.Mode = pf_auth.MODE_SMS_TWO_WAY_OTP_PLUS_PIN;
                //if (rbPhoneAppStandard.Checked) pfAuthParams.Mode = pf_auth.MODE_PHONE_APP_STANDARD;
                //if (rbPhoneAppPin.Checked) pfAuthParams.Mode = pf_auth.MODE_PHONE_APP_PIN;
                //if (rbPin.Checked || rbSmsTwoWayOtpPlusPin.Checked || rbPhoneAppPin.Checked)
                //{
                //    if (rbSha1.Checked)
                //    {
                //        // Generate a random string for the salt
                //        byte[] randomArray = new byte[8];
                //        string randomString;
                //        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                //        rng.GetBytes(randomArray);
                //        randomString = Convert.ToBase64String(randomArray);

                //        string pin = txtPin.Text;
                //        string salt = randomString;
                //        byte[] saltedPinByteArray = Encoding.UTF8.GetBytes(pin + salt);
                //        SHA1CryptoServiceProvider sha1CryptoServiceProvider = new SHA1CryptoServiceProvider();
                //        string sha1PinHash = BitConverter.ToString(sha1CryptoServiceProvider.ComputeHash(saltedPinByteArray)).Replace("-", "").ToLower();
                //        pfAuthParams.Sha1PinHash = sha1PinHash;
                //        pfAuthParams.Sha1Salt = salt;
                //    }
                //    else
                //    {
                //        pfAuthParams.Pin = txtPin.Text;
                //    }
                //}
                //if (rbSmsTwoWayOtp.Checked) pfAuthParams.SmsText = "<$otp$>\nReply with this one-time passcode to complete your authentication.";
                //if (rbSmsTwoWayOtpPlusPin.Checked) pfAuthParams.SmsText = "<$otp$>\nReply with this one-time passcode and your PIN to complete your authentication.";
                pfAuthParams.Hostname = "TestHostName";
                pfAuthParams.IpAddress = "255.255.255.255";
                pfAuthParams.CertFilePath = "C:\\Users\\Alicia\\Dropbox\\IT-Tallaght\\Dissertation\\TestApplications\\MFAAzureTest\\App_Code\\pf\\certs\\cert_key.p12";

                bool res = pf_auth.pf_authenticate(pfAuthParams, out otp, out callStatus, out errorId);

                // the return value from the above function is a boolean that is the result of
                // the authentication.  Two out arguments are also returned.  The first is the
                // result of the phonecall itself, the second is the result of the connection
                // with the PhoneFactor backend.  See call_results.txt for a list of call results
                // and descriptions that correspond to value returned.
                //Label1.Text = res.ToString();
                //Label2.Text = otp;
                //Label3.Text = callStatus.ToString();
                //Label4.Text = errorId.ToString();
              
                if (res)
                {
                    Response.Redirect("~/");
                }
                else
                {
                    //ModelState.AddModelError("NewPassword");
                }
            }
        }


        //public IEnumerable<OpenAuthAccountData> GetExternalLogins()
        //{
        //    var accounts = OpenAuth.GetAccountsForUser(User.Identity.Name);
        //    CanRemoveExternalLogins = CanRemoveExternalLogins || accounts.Count() > 1;
        //    return accounts;
        //}

        //public void RemoveExternalLogin(string providerName, string providerUserId)
        //{
        //    var m = OpenAuth.DeleteAccount(User.Identity.Name, providerName, providerUserId)
        //        ? "?m=RemoveLoginSuccess"
        //        : String.Empty;
        //    Response.Redirect("~/Account/Manage" + m);
        //}


        protected static string ConvertToDisplayDateTime(DateTime? utcDateTime)
        {
            // You can change this method to convert the UTC date time into the desired display
            // offset and format. Here we're converting it to the server timezone and formatting
            // as a short date and a long time string, using the current thread culture.
            return utcDateTime.HasValue ? utcDateTime.Value.ToLocalTime().ToString("G") : "[never]";
        }
    }
}